package cn.edu.zstu.qingzhu.qingzhushop.listener;

import cn.edu.zstu.qingzhu.qingzhushop.entity.Log;
import cn.edu.zstu.qingzhu.qingzhushop.service.ILogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AbstractAuthenticationFailureEvent;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author ShenTuZhiGang
 * @version 1.0.0
 * @date 2020-08-02 13:52
 */
@Component
@Slf4j
public class AuthenticationFailureListener
        implements ApplicationListener<AbstractAuthenticationFailureEvent> {
    @Autowired
    ILogService iLogService;

    @Override
    public void onApplicationEvent(AbstractAuthenticationFailureEvent event) {
        Object username = event.getAuthentication().getPrincipal();
        Object credentials = event.getAuthentication().getCredentials();
        Object details = event.getAuthentication().getDetails();
        String ip = ((WebAuthenticationDetails) details).getRemoteAddress();
        Log loginLog = new Log();
        loginLog.setOperation("登录");
        loginLog.setType("login");
        loginLog.setIp(ip);
        loginLog.setOperator((String) username);
        loginLog.setTime(LocalDateTime.now());
        loginLog.setStatus("failure");
        loginLog.setRemark("登录失败:" + event.getException().getMessage());
        iLogService.save(loginLog);
        log.warn("Failed login using USERNAME [" + username + "]");
        log.warn("Failed login using PASSWORD [" + credentials + "]");
    }
}
